package com.ogilvy.audi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.ogilvy.audi.service.GuestUserManager;
import com.ogilvy.audi.model.GuestUser;
import com.ogilvy.audi.webapp.action.BaseAction;

import java.util.List;

public class GuestUserAction extends BaseAction implements Preparable {
    private GuestUserManager guestUserManager;
    private List guestUsers;
    private GuestUser guestUser;
    private Long id;
    private String query;

    public void setGuestUserManager(GuestUserManager guestUserManager) {
        this.guestUserManager = guestUserManager;
    }

    public List getGuestUsers() {
        return guestUsers;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String guestUserId = getRequest().getParameter("guestUser.id");
            if (guestUserId != null && !guestUserId.equals("")) {
                guestUser = guestUserManager.get(new Long(guestUserId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        guestUsers = guestUserManager.search(query, GuestUser.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public GuestUser getGuestUser() {
        return guestUser;
    }

    public void setGuestUser(GuestUser guestUser) {
        this.guestUser = guestUser;
    }

    public String delete() {
        guestUserManager.remove(guestUser.getId());
        saveMessage(getText("guestUser.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            guestUser = guestUserManager.get(id);
        } else {
            guestUser = new GuestUser();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (guestUser.getId() == null);

        guestUserManager.save(guestUser);

        String key = (isNew) ? "guestUser.added" : "guestUser.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}